package com.pansoft.openplanet.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AirDropDetail;
import com.pansoft.openplanet.bean.AirDropModel;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.fragment.AirDropRecyclerViewAdapter;
import com.pansoft.openplanet.fragment.BottomWalletChooseDialogFragment;
import com.pansoft.openplanet.util.TCMathUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.app.DialogFragment.STYLE_NO_FRAME;


/**
 * 空投场详情
 * Created by yqs on 2018/07/27
 */

public class AirDropDetailActivity extends TCBaseActivity implements View.OnClickListener {
    public static final String TAG = "AirDropDetailActivity";

    private ImageView ivImage;
    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    private TextView tvDays;
    private TextView tvItem2;
    private TextView tvHour;
    private TextView tvItem4;
    private TextView tvMinute;
    private TextView tvSecond;
    private TextView tvAirTitle;
    private TextView tvTeamName;
    private TextView tvContractAddress;
    private TextView tvAirInfo;
    private Button button;
    private TextView tvAssetName;


    private TimeCount timeCount;
    private int airDropId;
    private AirDropDetail.AirportBean airportBean;
    private TextView tvStartText;


    public static void start(Context context, int airDropId) {
        Intent starter = new Intent(context, AirDropDetailActivity.class);
        starter.putExtra("airDropId", airDropId);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_airdrop_detail);
        initView();
        initData();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
        if (timeCount != null) {
            timeCount.cancel();
        }
    }


    @SuppressLint("WrongViewCast")
    private void initView() {
        ivImage = (ImageView) findViewById(R.id.iv_image);
        tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        tv3 = (TextView) findViewById(R.id.tv3);
        tvDays = (TextView) findViewById(R.id.tv_item1);
        tvItem2 = (TextView) findViewById(R.id.tv_item2);
        tvHour = (TextView) findViewById(R.id.tv_item3);
        tvItem4 = (TextView) findViewById(R.id.tv_item4);
        tvMinute = (TextView) findViewById(R.id.tv_item5);
        //tvSecond = (TextView) findViewById(R.id.tv_item7);
        tvAirTitle = (TextView) findViewById(R.id.tv_air_title);
        tvTeamName = (TextView) findViewById(R.id.tv_team_name);
        tvContractAddress = (TextView) findViewById(R.id.tv_contract_address);
        tvAirInfo = (TextView) findViewById(R.id.tv_air_info);
        button = (Button) findViewById(R.id.button);
        button.setClickable(false);
        button.setOnClickListener(this);
        tvAssetName = (TextView) findViewById(R.id.tv_asset_name);
        tvStartText = (TextView) findViewById(R.id.tv3);
    }

    private void initData() {
        airDropId = getIntent().getIntExtra("airDropId", 0);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_airdrop_detail));
        ImageView iv_right = (ImageView) findViewById(R.id.iv_detail);
        iv_right.setImageDrawable(getResources().getDrawable(R.drawable.right_top_import_menu));
        requestData();


    }

    private void requestData() {
        showLoading(R.string.common_text_please_wait);
        final HashMap<String, String> map = new HashMap<>();
        map.put("id", airDropId + "");
        map.put("userId", EnvironmentVariable.getUserName());

        TCRequestUtil.getCommonRequest(TAG, "aridrop/airportDetails", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                dismissLoading();
                AirDropDetail detail = null;
                try {
                    detail = new Gson().fromJson(response, AirDropDetail.class);
                    if (detail == null) {
                        ToastUtils.showShort(R.string.common_text_http_request_fail);
                        return;
                    }
                    if ("success".equals(detail.getResult())) {
                        updateView(detail);

                    } else {
                        ToastUtils.showShort(R.string.common_text_http_request_fail);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.common_text_http_request_fail);
                }

            }

            @Override
            public void onFail(String error) {
                dismissLoading();
                ToastUtils.showShort(R.string.common_text_http_request_fail);

            }
        });
    }

    private void updateView(AirDropDetail detail) {
        airportBean = detail.getAirport();
        if (airportBean == null) {
            return;
        }
        button.setClickable(true);
        tvAirTitle.setText(detail.getAirport().getBrief());
        tvAssetName.setText(airportBean.getCoinName());
        tvContractAddress.setText(airportBean.getContractAddress());
        tvTeamName.setText(airportBean.getOrganization());
        tvAirInfo.setText(airportBean.getDetail());
        tvDays.setText(AirDropRecyclerViewAdapter.convertToString(airportBean.getEndTimeOfDay()));
        tvMinute.setText(AirDropRecyclerViewAdapter.convertToString(airportBean.getEndTimeOfMinute()));
        tvHour.setText(AirDropRecyclerViewAdapter.convertToString(airportBean.getEndTimeOfHour()));

        String allCount = TCMathUtil.retainAsignDecimals(airportBean.getTokenNumber(), 8);
        tv2.setText(allCount);

        tv1.setText(TCMathUtil.retainAsignDecimals(airportBean.getDistributionNumber(), 8));
        int state = airportBean.getStatus();


        //如果未开始
        if (state == AirDropModel.STATE_UNSTART) {
            long startTime = airportBean.getStartTime();
            if (startTime - System.currentTimeMillis() > 0) {
                long countDownInterval = 1000 * 60;
                if (startTime - System.currentTimeMillis() < 1000 * 60 * 120) {
                    //一秒刷新一次
                    countDownInterval = 1000;
                }
                timeCount = new TimeCount(startTime - System.currentTimeMillis(), countDownInterval);//构造CountDownTimer对象
                timeCount.start();
            }

        } else {
            //已经开始
            long endTime = airportBean.getEndTime();
            if (endTime - System.currentTimeMillis() > 0) {
                long countDownInterval = 1000 * 60;
                if (endTime - System.currentTimeMillis() < 1000 * 60 * 120) {
                    //一秒刷新一次
                    countDownInterval = 1000;
                }
                timeCount = new TimeCount(endTime - System.currentTimeMillis(), countDownInterval);//构造CountDownTimer对象
                timeCount.start();
            }
        }


        if (state == AirDropModel.STATE_STARTED) {
            button.setText(ResStringUtil.getString(R.string.air_drop_detail_but_text));
            tvStartText.setText(ResStringUtil.getString(R.string.open_planet_airdrop_before_end));
            button.setBackgroundColor(getResources().getColor(R.color.op_text_accent_color));
        } else if (state == AirDropModel.STATE_UNSTART) {
            button.setText(ResStringUtil.getString(R.string.open_planet_airdrop_state_not_start));
            tvStartText.setText(ResStringUtil.getString(R.string.open_planet_airdrop_before_begin));
            //  button.setClickable(false);
            button.setBackgroundColor(getResources().getColor(R.color.gray_bg));
        } else if (state == AirDropModel.STATE_STOP) {
            button.setText(ResStringUtil.getString(R.string.open_planet_airdrop_state_end));
            //  button.setClickable(false);
            button.setBackgroundColor(getResources().getColor(R.color.gray_bg));
        } else {
            button.setText(ResStringUtil.getString(R.string.open_planet_airdrop_state_out));
            //  button.setClickable(false);
            button.setBackgroundColor(getResources().getColor(R.color.gray_bg));
        }

        if (airportBean.getFlag() == 1) {
            //已经抢过
            button.setText(ResStringUtil.getString(R.string.open_planet_airdrop_state_had));
            button.setBackgroundColor(getResources().getColor(R.color.gray_bg));
        }
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.button) {
            if (airportBean.getFlag() == 1) {
                //已经抢过
                ToastUtils.showShort(R.string.open_planet_airdrop_had_and_check);
                return;
            }

            //马上抢
            int state = airportBean.getStatus();
            if (state == AirDropModel.STATE_UNSTART) {
                ToastUtils.showShort(getString(R.string.open_planet_airdrop_state_long,
                        ResStringUtil.getString(R.string.open_planet_airdrop_state_not_start)));
                return;
            } else if (state == AirDropModel.STATE_STOP) {
                ToastUtils.showShort(getString(R.string.open_planet_airdrop_state_long,
                        ResStringUtil.getString(R.string.open_planet_airdrop_state_end)));
                return;
            } else if (state == AirDropModel.STATE_NO_ENOUGH) {
                ToastUtils.showShort(getString(R.string.open_planet_airdrop_state_long,
                        ResStringUtil.getString(R.string.open_planet_airdrop_state_out)));
                return;
            }
            showWalletChoose();
        }
    }

    /**
     * 切换钱包
     */
    private void showWalletChoose() {
        List<WalletBean> walletBeans = new ArrayList<>();
        String receiveAddress = null;

        IPAssetsConstant.ChainEnum blockChainEnum = IPAssetsConstant.ChainEnum.ETH;
        if (airportBean.getBlockchainId().equals(String.valueOf(IPAssetsConstant.CHAIN_ID_TURBOCHAIN))) {

            receiveAddress = new AccountDao(this).getMainAccount().getAddress();
            goToNext(receiveAddress);
            return;
        }
        if (airportBean.getBlockchainId().equals(String.valueOf(IPAssetsConstant.CHAIN_ID_BTC))) {
            blockChainEnum = IPAssetsConstant.ChainEnum.BTC;
        }
        if (airportBean.getBlockchainId().equals(String.valueOf(IPAssetsConstant.CHAIN_ID_EOSTEST))) {
            blockChainEnum = IPAssetsConstant.ChainEnum.EOSTEST;
        }
        if (airportBean.getBlockchainId().equals(String.valueOf(IPAssetsConstant.CHAIN_ID_EOS))) {
            blockChainEnum = IPAssetsConstant.ChainEnum.EOS;

        }
        List<Account> accountList = new AccountDao(this).getAllChildAccount(blockChainEnum.chainName);
        if (accountList != null) {
            for (int i = 0; i < accountList.size(); i++) {
                Account account = accountList.get(i);
                if (account.getAccountType() == Account.ACCOUNT_TYPE_OBSERVE) {
                    //观察钱包不能转账
                    continue;
                }
                WalletBean walletBean = new WalletBean.Builder()
                        .accountName(account.getAcccountName())
                        .avatar(account.getAccountAvatar())
                        .address(account.getAddress())
                        .balance("0")
                        .build();

                walletBeans.add(walletBean);
            }
        }
        if (walletBeans.size() == 0) {
            ToastUtils.showShort(R.string.open_planet_create_wallet_first);
            return;
        }
        BottomWalletChooseDialogFragment bottomWalletChooseDialogFragment = new
                BottomWalletChooseDialogFragment();
        bottomWalletChooseDialogFragment.setData(this, walletBeans, IPAssetsConstant.CHAIN_ID_ETH);
        bottomWalletChooseDialogFragment.setStyle(STYLE_NO_FRAME, 0);
        bottomWalletChooseDialogFragment.show(getSupportFragmentManager(), "WalletChoose");
        bottomWalletChooseDialogFragment.hideBalace(true);
        bottomWalletChooseDialogFragment.setOnWalletSelectChangedListener(new BottomWalletChooseDialogFragment.OnWalletSelectChangedListener() {
            @Override
            public void onWalletChanged(WalletBean walletBean) {
                String receiveAddress = walletBean.getAddress();

                goToNext(receiveAddress);
            }
        });
    }

    public void goToNext(String address) {
        AirDropTaskResultActivity.start(AirDropDetailActivity.this, address, airportBean);
    }

    /* 定义一个倒计时的内部类 */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            int state = airportBean.getStatus();
            if (state == AirDropModel.STATE_UNSTART) {
                airportBean.setStatus(AirDropModel.STATE_STARTED);
                button.setText(ResStringUtil.getString(R.string.air_drop_detail_but_text));
                tvStartText.setText(ResStringUtil.getString(R.string.open_planet_airdrop_before_end));

                button.setBackgroundColor(getResources().getColor(R.color.op_text_accent_color));
                long endTime = airportBean.getEndTime();
                if (endTime - System.currentTimeMillis() > 0) {
                    long countDownInterval = 1000 * 60;
                    if (endTime - System.currentTimeMillis() < 1000 * 60 * 120) {
                        //一秒刷新一次
                        countDownInterval = 1000;
                    }
                    timeCount = new TimeCount(endTime - System.currentTimeMillis(), countDownInterval);//构造CountDownTimer对象
                    timeCount.start();
                }
            } else {
                if (state == AirDropModel.STATE_STARTED) {
                    airportBean.setStatus(AirDropModel.STATE_STOP);
                    button.setText(ResStringUtil.getString(R.string.open_planet_airdrop_state_end));
                    button.setBackgroundColor(getResources().getColor(R.color.gray_bg));
                }
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
//            if (millisUntilFinished <= 0) {
//                timeCount.onFinish();
//                timeCount.cancel();
//                return;
//            }
            int leftDay = (int) (millisUntilFinished / (1000 * 60 * 60 * 24));
            int leftHour = (int) (millisUntilFinished - (leftDay * 1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            int leftMinute = (int) (millisUntilFinished - (leftDay * 1000 * 60 * 60 * 24)
                    - leftHour * (1000 * 60 * 60)) / (1000 * 60);
            com.utilcode.util.LogUtils.i(leftDay + "", leftHour + "", leftMinute + "");
            tvDays.setText(AirDropRecyclerViewAdapter.convertToString(leftDay));
            tvMinute.setText(AirDropRecyclerViewAdapter.convertToString(leftMinute));
            tvHour.setText(AirDropRecyclerViewAdapter.convertToString(leftHour));
        }
    }
}